<template>
  <div>
    <input ref="fileInput" multiple type="file" accept="image/*" style="display: none" @change="getFile">
    <div style="margin-top:10px">
      <el-button :disabled="dataLoading" size="mini" type="primary" @click.native="handleAdd">上传</el-button>
      <el-button :disabled="dataLoading" size="mini" type="primary" @click.native="handleDel">删除</el-button>
      <el-button :disabled="dataLoading" size="mini" type="primary" @click.native="reUploadBatch">重新上传</el-button>
    </div>
    <table-box
      ref="refTable"
      table-size="mini"
      :table-config="tableConfig"
      show-selection
      show-index
      :off-set="-20"
      :show-custom-setting="false"
      :data="fileList"
      :selected-arry.sync="tableSelected"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column reuqired fixed="right" min-width="130" label="操作">
        <template slot-scope="scope">
          <el-button v-show="!scope.row.isFail" size="mini" type="text" @click.native="handlePreview(scope.row,scope.$index)">预览</el-button>
          <el-button v-show="scope.row.isFail" style="color:#F56C6C" size="mini" type="text" @click.native="handleReUpload(scope.row,scope.$index)">重新上传</el-button>
        </template>
      </el-table-column>
    </table-box>
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showViewer"
      :on-close="handleCloseImg"
      :url-list="urlList"
    />
  </div>

</template>

<script>

import BackPageMixin from '@/mixins/backPage'
import { fileUploadBatch } from '@/api/common'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import { filterURL } from '@/utils'
export default {
  name: 'FileExportBatch',
  components: { ElImageViewer },
  mixins: [BackPageMixin],
  props: {

  },
  data() {
    return {
      submiting: false,
      uploadLoading: false,
      fileList: [],
      typeOptions: [],
      showViewer: false,
      dataLoading: false,
      url: process.env.VUE_APP_Img_prefix,
      urlList: [],
      tableSelected: [],
      tableConfig: {
        interfacePath: ``,
        buttonGroupCode: 'fileBatch',
        hideSearchBar: true,
        tabIndex: 1,
        flagFlag: false,
        // 表格字段动态配置
        setting: [
          {
            prop: 'attachmentUrl',
            label: '图片预览',
            width: '100',
            type: 'hidden',
            render: (h, row) => {
              if (!row.attachmentUrl) return ''
              return h('el-image', {
                attrs: {
                  src: `${process.env.VUE_APP_IMG_PREFIX}` + row.attachmentUrl,
                  height: 30,
                  previewSrcList: [`${process.env.VUE_APP_IMG_PREFIX}` + row.attachmentUrl]
                }
              })
            }
          },
          {
            prop: 'attachmentName',
            label: '问题描述',
            minWidth: '150'
          },
          {
            prop: 'createTime',
            label: '上传时间',
            width: '200'
          },
          {
            prop: 'createBy',
            label: '上传人',
            width: '200'
          }
        ],
        btnList: []
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
  },

  methods: {
    getFileList() {
      return this.fileList
    },
    handleAdd(data) {
      if (this.fileList.length > 100) {
        this.$message.warning('一次最多保存100条，请先保存后再添加')
        return
      }
      this.$refs.fileInput.click()
    },
    chunk(obj, size) {
      let arr = []
      size === 10 ? arr = Object.values(obj) : arr = obj.map(v => v.files)
      const result = []
      for (let i = 0, len = arr.length; i < len; i += size) {
        result.push(arr.slice(i, i + size))
      }
      return result
    },
    // 获取文件数据
    getFile(event) {
      const list = event.target.files
      if (list.length === 0) return
      if (list.length > 100) {
        this.$message.warning('所选文件个数超过100个，不能上传')
        return
      }

      this.uploadLoading = true
      const arrList = this.chunk(list, 10)
      Promise.all(arrList.map(v => this.uploadItem(v))).then(res => {
        this.uploadLoading = false
      })
    },
    uploadItem(i) {
      // 调用接口
      return new Promise(resolve => {
        const dataList = new FormData()
        i.forEach(v => dataList.append('files', v))
        fileUploadBatch(dataList).then(response => {
          response.data.forEach(el => {
            const imgItem = {
              attachmentUrl: (el && el.attachmentUrl) || '', // 产品图片文件路径
              addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
              attachmentName: el && el.attachmentName, // 文件名attachmentName
              createBy: (el && el.createBy) || '', // 创建人
              createTime: (el && el.createTime) || '' // 创建时间
            }
            this.fileList.push(imgItem)
          })
          resolve(true)
        }).catch(v => {
          const param = []
          for (var value of dataList.values()) {
            param.push(value)
          }
          param.forEach(el => {
            const imgItem = {
              files: el, // 文件,
              remark: el.size / 1024 / 1024 > 100 ? '单个文件大小超出100M' : '',
              url: '', // 产品图片文件路径
              addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
              isFail: 1,
              attachmentName: el.name, // 文件名
              createTime: '' // 创建时间
            }
            this.fileList.unshift(imgItem)
          })
          resolve(true)
        })
      })
    },
    handlePreview(file) {
      // const test = 'http://fbpm.quanyou.com.cn/V2017files/2020/12/07/经销商档案新建流程/d6d98b4c-ff7a-4818-b4b4-e70bf46293ba~1.docx'
      // if (file.pictureUrl.substring(0, 11) === 'http://fbpm') {
      //   window.open(file.pictureUrl)
      //   return
      // }
      const fileExtension = file.attachmentUrl.substring(file.attachmentUrl.lastIndexOf('.') + 1).toLowerCase()
      if (fileExtension === 'jpg' || fileExtension === 'jpeg' || fileExtension === 'png' || fileExtension === 'gif' || fileExtension === 'bmp') {
      // 图片预览
        if (file.attachmentUrl.substring(0, 11) === 'http://fbpm') {
          window.open(file.attachmentUrl)
          return
        }
        this.urlList = []
        this.showViewer = true
        this.urlList.push(filterURL(file.attachmentUrl))
        console.log('完整附件路径', this.urlList, file.attachmentUrl)
      } else if (fileExtension === 'doc' || fileExtension === 'docx' || fileExtension === 'xlsx' || fileExtension === 'pdf' || fileExtension === 'pptx') {
        // window.open(`${process.env.VUE_APP_OFFICE_PREFIX}?src=` + process.env.VUE_APP_Img_prefix + file.path)
        window.open(`${process.env.VUE_APP_OFFICE_PREFIX}?src=` + filterURL(file.attachmentUrl))
      } else {
        this.$message.warning(fileExtension + '该文件类型不支持预览')
      }
    },
    // 重新批量上传
    reUploadBatch() {
      if (!this.singleJudge(this.tableSelected, '上传', false)) {
        return
      }
      const temp = this.tableSelected.filter(v => !v.isFail)
      if (temp.length > 0) {
        this.$message.warning('所选项包括上传成功的文件,请重新选择')
        return
      }

      const arrList = this.chunk(this.tableSelected, 5)
      for (let i = 0; i < arrList.length; i++) {
        const dataList = new FormData()
        arrList[i].forEach(v => dataList.append('files', v))
        this.dataLoading = true

        // 1、先将需要重新上传的文件从列表中删除
        const flag = this.fileList.filter(item => {
          const index = this.tableSelected.findIndex(i => (i.addFlag && item.addFlag && i.addFlag === item.addFlag))
          return index === -1
        })
        this.fileList = flag
        // 2、重新上传删除的文件
        fileUploadBatch(dataList).then(response => {
          response.data.forEach(el => {
            const imgItem = {
              attachmentName: (el && el.attachmentName) || '', // 附件名
              attachmentUrl: el && el.attachmentUrl, // 文件路径
              id: el.id,
              addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
              createTime: (el && el.createTime) || '', // 创建时间
              createBy: (el && el.createBy) || '', // 创建人
              dr: (el && el.dr) || 0 // 删除标志
            }
            console.log('上传后的', imgItem)
            this.fileList.push(imgItem)
            this.dataLoading = false
          })
        }).catch(v => {
          this.dataLoading = false
          const param = []
          for (var value of dataList.values()) {
            param.push(value)
          }
          param.forEach(el => {
            const imgItem = {
              files: el, // 文件
              remark: el.size / 1024 / 1024 > 100 ? '单个文件大小超出100M' : '',
              url: '', // 产品图片文件路径
              addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
              isFail: 1,
              attachmentName: el.attachmentName, // 文件名
              createTime: '' // 创建时间
            }
            this.fileList.unshift(imgItem)
          })
        })
      }
    },
    handleReUpload(file, index) {
      const formFile = new FormData()
      formFile.append('files', file.files)
      fileUploadBatch(formFile).then(response => {
        if (response.success) {
          response.data.forEach(el => {
            const imgItem = {
              attachmentName: (el && el.attachmentName) || '', // 附件名
              attachmentUrl: el && el.attachmentUrl, // 文件路径
              id: el.id,
              addFlag: Math.floor(Math.random() * 0xffffff).toString(16),
              createTime: (el && el.createTime) || '', // 创建时间
              createBy: (el && el.createBy) || '', // 创建人
              dr: (el && el.dr) || 0 // 删除标志
            }
            this.fileList.splice(index, 1, imgItem)
          })
          this.dataLoading = false
        }
      }).catch(v => {
        this.dataLoading = false
      })
    },
    selectionChangeHandle(data) {
      this.tableSelected = data
    },
    handleCloseImg() {
      this.showViewer = false
    },
    handleDel() {
      if (!this.singleJudge(this.tableSelected, '删除', false)) {
        return
      }
      const flag = this.fileList.filter(item => {
        const index = this.tableSelected.findIndex(i => (i.addFlag && item.addFlag && i.addFlag === item.addFlag))
        return index === -1
      })
      this.fileList = flag
    }
  }
}
</script>
<style lang='scss' scoped>
/deep/ .el-breadcrumb__inner{
    color: $qup-color-primary;
  }
/deep/.el-icon-circle-close:before{
  color: white
}
</style>
